package com.example.demo.utils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class SFTPUtils {
    private static final Logger logger = LoggerFactory.getLogger(SFTPUtils.class);

    @PostConstruct
    public void init() {
        downloadExample("1767740260516630530/测试报告附件20240313103135.pdf", "测试报告附件20240313103135.pdf");
//        downloadExample("1764217798386905090/宣讲会-接口对接方案.png","宣讲会-接口对接方案.png");
    }

    public static void downloadExample(String remoteFilePath, String fileName) {
        String host = "10.255.103.250";
        int port = 18083; // SFTP默认端口是22
        String user = "gansu";
        String password = "Jzhcspt%!25gansu";
        String localFilePath = "/app/xqgl/xqgl-test/file/download/" + fileName;
//        String remoteFilePath = "1.txt";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();

            channelSftp = (ChannelSftp) channel;

            channelSftp.get(remoteFilePath, localFilePath);
        } catch (Exception e) {
            logger.error("{}", e);
        } finally {
            if (channelSftp != null) {
                channelSftp.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

}
